package com.ccc.controller;


import com.ccc.entity.StuCheck;
import com.ccc.mapper.StuCheckMapper;
import com.ccc.mapper.StuLeaveMapper;
import com.ccc.utils.JwtUtil;
import com.ccc.utils.ResponseResult;
import io.jsonwebtoken.Claims;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.GetMapping;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;

/**
 * <p>
 * 前端控制器
 * </p>
 *
 * @author ccc
 * @since 2021-12-27
 */
@Controller
public class StuCheckController {

    @Autowired
    StuCheckMapper stuCheckMapper;

    /**
     * 教师请求学生打卡列表，返回的是所有学生的打卡信息
     *
     * @return
     */
    @GetMapping("/teacher/checklist")
    @PreAuthorize("hasAuthority('teacher')")
    @ResponseBody
    public ResponseResult checkList() {
        return new ResponseResult(200, "success", stuCheckMapper.checkList());
    }

    /**
     * 学生请求打卡列表，返回的是请求学生的打卡信息
     *
     * @param request 用于获取token解析出学生的id（username）
     * @return
     */
    @GetMapping("/stu/checklist")
    @PreAuthorize("hasAuthority('student')")
    @ResponseBody
    public ResponseResult stuCheckList(HttpServletRequest request) {
        String token = request.getHeader("token");

        String username;
        try {
            Claims claims = JwtUtil.parseJWT(token);
            username = claims.getSubject();
        } catch (Exception e) {
            e.printStackTrace();
            return new ResponseResult(400, "token Error!");
        }

        return new ResponseResult(200, "success", stuCheckMapper.checkListById(username));

    }


    /**
     * 学生添加打卡信息
     *
     * @param stuCheck
     * @param request
     * @return
     */
    @PostMapping("/stu/addCheck")
    @PreAuthorize("hasAuthority('student')")
    @ResponseBody
    public ResponseResult addCheck(@RequestBody StuCheck stuCheck, HttpServletRequest request) {
        String token = request.getHeader("token");
        String username;
        try {
            Claims claims = JwtUtil.parseJWT(token);
            username = claims.getSubject();
        } catch (Exception e) {
            e.printStackTrace();
            return new ResponseResult(400, "token Error!");
        }

        stuCheckMapper.addCheck(username, stuCheck.getTemperature(), stuCheck.getHealthCode(), stuCheck.getCheckAddress());
        return new ResponseResult(200, "success");

    }

}
